package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AduserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AduserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AduserService {
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //校验参数
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名和密码是必须的");
        }
        //数据库查找用户信息
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (user == null) CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "没找到相关用户");

        //校验密码用户名
        String s = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes(StandardCharsets.UTF_8));
        if (!s.equalsIgnoreCase(user.getPassword())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名密码不匹配");
        }

        //判断用户状态
        if (user.getStatus() != 9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "用户状态异常");
        }
        //修改最近登录时间
        user.setLoginTime(new Date());
        boolean b = this.updateById(user);
        //颁发tocken
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        AdUserVO vo = new AdUserVO();
        BeanUtils.copyProperties(user, vo);

        //响应结果
        Map m = new HashMap<String, Object>();
        m.put("token", token);
        m.put("user", vo);
        return ResponseResult.okResult(m);
    }
}
